<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
	<!-- Basic Page Needs -->
	<meta charset="utf-8">
	<title>电影列表</title>
	<meta name="description" content="A Template by Gozha.net">
	<meta name="keywords" content="HTML, CSS, JavaScript">
	<meta name="author" content="Gozha.net">

	<!-- Mobile Specific Metas-->
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta content="telephone=no" name="format-detection">
	
	<link rel="stylesheet" href="layui/css/layui.css" media="all">

	<!-- Fonts -->
	<!-- Font awesome - icon font -->
	<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
	<!-- Roboto -->
	<link href='http://fonts.useso.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>

	<!-- Stylesheets -->
	<!-- jQuery UI -->
	<link href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet">

	<!-- Mobile menu -->
	<link href="css/gozha-nav.css" rel="stylesheet" />
	<!-- Select -->
	<link href="css/external/jquery.selectbox.css" rel="stylesheet" />
	
	<link href="css/style-before.css?v=1" rel="stylesheet" />

	<!-- Custom -->
	<link href="css/style.css?v=1" rel="stylesheet" />

	<!-- Modernizr -->
	<script src="js/external/modernizr.custom.js"></script>

	<!-- REVOLUTION BANNER CSS SETTINGS -->
	<link rel="stylesheet" type="text/css" href="rs-plugin/css/settings.css" media="screen" />
	<script type="text/javascript" src="js/jquery-2.0.3.js"></script>
	
	<script type="text/javascript" src="js/jquerysession.js"></script>
</head>

<body>
	<div class="wrapper">
		<!-- Header section -->
		<jsp:include page="header-general.jsp"></jsp:include>

		<!-- Search bar -->
		<div class="search-wrapper">
			<div class="container container--add">
				<form id='search-form' method='get' class="search">
					<input type="text" id="search-content" class="search__field" placeholder="搜索正在热映的电影"> 
						<select name="sorting_item" id="search-sort" class="search__sort" tabindex="0">
							<option value="电影名" selected='selected'>根据电影名</option>
							<option value="类型">根据电影类型</option>
							<option value="导演">根据导演</option>
							<option value="主演">根据演员</option>
							<option value="地区">根据地区</option>
							<option value="语言">根据语言</option>
						</select>
					<button type='button' id="btnsearch" class="btn btn-md btn--danger search__button"
						style="margin-right: 50px;">搜索电影</button>
				</form>
			</div>
		</div>
		<!-- Main content -->
		<section class="container">
			<div class="col-sm-8 col-md-9">
				<h2 class="page-heading" id="titlecount"></h2>

				<div class="tags-area">
					<div class="tags tags--unmarked">
						<span class="tags__label">排 序:</span>
						<ul>
							<li class="item-wrap"><a href="javascript:;"
								onclick="ordermovie('all',1)" id="orderall" class="tags__item item-active">全部</a></li>
							<li class="item-wrap"><a href="javascript:;"
								onclick="ordermovie('release',1)" id="orderrelease" class="tags__item">上映时间</a></li>
							<li class="item-wrap"><a href="javascript:;"
								onclick="ordermovie('popularity',1)" id="orderpopularity" class="tags__item">影评数</a></li>
							<li class="item-wrap"><a href="javascript:;"
								onclick="ordermovie('comments',1)" id="ordercomments" class="tags__item">人气</a></li>
						</ul>
					</div>
				</div>

				<!-- Movie preview item -->
				<div class="movie movie--preview release" id="playingmovie"></div>

				<div class="coloum-wrapper" id="fenye"></div>
				
			</div>

			<aside class="col-sm-4 col-md-3">
					<div class="sitebar">
						<div class="category category--discuss category--count marginb-sm mobile-category ls-cat">
							<h3 class="category__title">今日热销榜</h3>
							<ol id="moviestoday" style="padding-left:53px;">

							</ol>
						</div>

						<div class="category category--cooming category--count marginb-sm mobile-category rs-cat">
							<h3 class="category__title">即将上映高分榜</h3>
							<ol id="moviessoon" style="padding-left:53px;">

							</ol>
						</div>
					</div>
			</aside>
		</section>
	</div>
				<!-- 获取总数 -->
		
	<div class="clearfix"></div>
		
	
    <jsp:include page="footer.jsp"></jsp:include>

		<input type="hidden" id="allcount">
		<input type="hidden" id="likecount">
	
	
		<!-- JavaScript-->
		<!-- jQuery 1.9.1-->
		<script src="http://ajax.useso.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
		<script>
			window.jQuery || document.write('<script src="js/external/jquery-1.10.1.min.js"><\/script>')
		</script>
		<!-- Migrate -->
		<script src="js/external/jquery-migrate-1.2.1.min.js"></script>
		<!-- jQuery UI -->
		<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
		<!-- Bootstrap 3-->
		<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
		<!-- jQuery REVOLUTION Slider -->
		<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.plugins.min.js"></script>
		<script type="text/javascript" src="rs-plugin/js/jquery.themepunch.revolution.min.js"></script>
		<!-- Mobile menu -->
		<script src="js/jquery.mobile.menu.js"></script>
		<!-- Select -->
		<script src="js/external/jquery.selectbox-0.2.min.js"></script>

		<!-- Stars rate -->
		<script src="js/external/jquery.raty.js"></script>

		<!-- Form element -->
		<script src="js/external/form-element.js"></script>
		<!-- Form validation -->
		<script src="js/form.js"></script>

		<!-- Custom -->
		<script src="js/customf.js"></script>
		  
		<script type="text/javascript" src="js/jquery.cookie.js"></script> 
		
		<script src="layui/layui.js" charset="utf-8"></script> 
		
		<jsp:include page="LoginAndRegister.jsp"></jsp:include>
		<jsp:include page="JudegeLogin.jsp"></jsp:include>
		
		<script src="js/custom.js"></script>

	<script type="text/javascript">
	    $(document).ready(function() {
	      init_Home();
	    });
	</script>
	
	<script type="text/javascript">
        $(document).ready(function() {
            init_MovieList();
        });
	</script>
		
	<script type="text/javascript">
		function MovieOrder(factor,page){
			var total = $("#allcount").val();
			var totalPage = getInt(total);
			$("#playingmovie").empty();
			$("#titlecount").empty();
			$("#titlecount").text("上映中"+"( "+total+" )");
			$.get("MovieByOrder?factor=" + factor + "&page=" + page,function(data) {
				$.each(data,function(i, o) {
					//查询电影的类别
					var movieType = getmtype(o.movieid);
					//获取电影的评分
					var movieScore = getmscore(o.movieid);
					//查询有多少人看过
					var ticketNum = getmtcount(o.movieid);
					//转时间
					o.releasedate = changeTime(o.releasedate);
					$("#playingmovie").append("<div class='col-sm-5 col-md-3'><div class='movie__images'>"
							+"<a href='movie-page-full.jsp?movieid="+o.movieid+"'><img alt='' src='"+o.moviepicture+"'></a></div></div>"
							+"<div class='col-sm-7 col-md-9'>"
							+"<a href='movie-page-left.jsp' class='movie__title link--huge'>"+o.moviename+"</a>"
							+"<p class='movie__time' style='position: absolute;margin-left: 105px;margin-top: 8px;'>"+o.duration+" 分钟</p>"
							+"<p class='movie__option'  style='margin-top: 10px;'>"
							+"<strong>地区：</strong><a href='#'>美国</a></p>"
							+"<p class='movie__option'><strong>语言：</strong><a href='#'>"+o.language+"</a></p>"
							+"<p class='movie__option'><strong>类别：</strong><a href='#'>"+movieType+"</a></p>"
							+"<p class='movie__option'><strong>上映日期：</strong>"+o.releasedate+"</p>"
							+"<p class='movie__option'><strong>导演：</strong><a href='#'>"+o.director+"</a></p>"
							+"<p class='movie__option'><strong>主演：</strong><a href='#'>"+o.mainactor+"</a></p>"
							+"<span class='movie__rate-number'>"+ticketNum+"人看过</span>"
							+"<div class='movie__btns'>"
							+"<a href='javascript:updmcoll("+o.movieid+");' style='font-size: 16px;' id='rate"+o.movieid+"'></a></div>"
							+"<div class='preview-footer'>"
							+"<div class='movie__rate'>"
							+"<div id='"+o.movieid+"' style='position: absolute;'></div><p></p>"
							+"<span class='movie__rating' style='margin-left: 10px;'>"+movieScore+"</span>"
							+"</div></div></div><div>&nbsp;</div><div>&nbsp;</div>");
					//给星星赋值
					layui.use('rate',function() {
						var rate = layui.rate;
						rate.render({
							elem : '#'+ o.movieid,
							value : movieScore,
							half : true //开启半星
							,
							readonly : true
						});
					});
					var userId = <%=session.getAttribute("userid")%>
					//判断用户是否有收藏，初始化界面
					$.ajax({
						url : "docoll",
						type : "POST",
						contentType : "application/json",
						data : JSON.stringify({
							users : {
								userid : userId
							},
							movies : {
								movieid : o.movieid
							}
						}),
						success : function(data) {
							if (data == 0) {
								$("#rate" + o.movieid).append(""
										+ "<i class='layui-icon layui-icon-star' style='font-size: 25px; color: rgb(255, 184, 0);'>"
										+ "</i>&nbsp;点击收藏");
							} else if (data != 0) {
								$("#rate" + o.movieid).append(""
										+ "<i class='layui-icon layui-icon-star-fill' style='font-size: 25px; color: rgb(255, 184, 0);'>"
									    + "</i>&nbsp;取消收藏");
							}

						},
						dataType : "json"
					});
				});
				var key = "nokey";
				var other = "";
				//清空
				$("#fenye").text("");
				//分页按钮拼接
				$("#fenye").append("<div class='pagination paginatioon--full'><a href='javascript:getPrevPage("+page+","+data.totalPage+",\""+key+"\",\""+factor+"\","+other+");' class='pagination__prev'>prev</a>"
						+"<a href='javascript:getNextPage("+page+","+totalPage+",\""+key+"\",\""+factor+"\","+other+");' class='pagination__next'>next</a></div>");
			});
		}
		
		function MovieByLike(select, key , page) {
			$.get("MovieLikeCount?key="+key+"&select="+select,function(data){
				console.log("data:"+data);
				$("#likecount").val(data);
				var total = $("#likecount").val();
				var totalPage = getInt(total);
				$("#playingmovie").empty();
				if(page == null){
					page = 1;
				}
				$("#titlecount").empty();
				$("#titlecount").text("上映中"+"( "+total+" )");
				$.get("MovieByUser?key="+key+"&select="+select+"&page="+page,function(data) {
					console.log(data);
					$.each(data,function(i, o) {
						//查询电影的类别
						var movieType = getmtype(o.movieid);
						//获取电影的评分
						var movieScore = getmscore(o.movieid);
						//查询有多少人看过
						var ticketNum = getmtcount(o.movieid);
						//转时间
						o.releasedate = changeTime(o.releasedate);
						$("#playingmovie").append("<div class='col-sm-5 col-md-3'><div class='movie__images'>"
								+"<a href='movie-page-full.jsp?movieid="+o.movieid+"'><img alt='' src='"+o.moviepicture+"'></a></div></div>"
								+"<div class='col-sm-7 col-md-9'>"
								+"<a href='movie-page-full.jsp?movieid="+o.movieid+"' class='movie__title link--huge'>"+o.moviename+"</a>"
								+"<p class='movie__time' style='position: absolute;margin-left: 105px;margin-top: 8px;'>"+o.duration+" 分钟</p>"
								+"<p class='movie__option'  style='margin-top: 10px;'>"
								+"<strong>地区：</strong><a href='#'>美国</a></p>"
								+"<p class='movie__option'><strong>语言：</strong><a href='#'>"+o.language+"</a></p>"
								+"<p class='movie__option'><strong>类别：</strong><a href='#'>"+movieType+"</a></p>"
								+"<p class='movie__option'><strong>上映日期：</strong>"+o.releasedate+"</p>"
								+"<p class='movie__option'><strong>导演：</strong><a href='#'>"+o.director+"</a></p>"
								+"<p class='movie__option'><strong>主演：</strong><a href='#'>"+o.mainactor+"</a></p>"
								+"<span class='movie__rate-number'>"+ticketNum+"人看过</span>"
								+"<div class='movie__btns'>"
								+"<a href='javascript:updmcoll("+o.movieid+");' style='font-size: 16px;' id='rate"+o.movieid+"'></a></div>"
								+"<div class='preview-footer'>"
								+"<div class='movie__rate'>"
								+"<div id='"+o.movieid+"' style='position: absolute;'></div><p></p>"
								+"<span class='movie__rating' style='margin-left: 10px;'>"+movieScore+"</span>"
								+"</div></div></div><div>&nbsp;</div><div>&nbsp;</div>");
						//给星星赋值
						layui.use('rate',function() {
							var rate = layui.rate;
							rate.render({
								elem : '#'+ o.movieid,
								value : movieScore,
								half : true //开启半星
								,
								readonly : true
							});
						});
					
					var userId = <%=session.getAttribute("userid")%>
					//判断用户是否有收藏，初始化界面
					$.ajax({
						url : "docoll",
						type : "POST",
						contentType : "application/json",
						data : JSON.stringify({
							users : {
								userid : userId
							},
							movies : {
								movieid : o.movieid
							}
						}),
						success : function(data) {
							if (data == 0) {
								$("#rate" + o.movieid).append(""
										+ "<i class='layui-icon layui-icon-star' style='font-size: 25px; color: rgb(255, 184, 0);'>"
										+ "</i>&nbsp;点击收藏");
							} else if (data != 0) {
								$("#rate" + o.movieid).append(""
										+ "<i class='layui-icon layui-icon-star-fill' style='font-size: 25px; color: rgb(255, 184, 0);'>"
									    + "</i>&nbsp;取消收藏");
							}

						},
						dataType : "json"
					});
				});
					var other = "";
					//清空
					$("#fenye").text("");
					//分页按钮拼接
					$("#fenye").append("<div class='pagination paginatioon--full'><a href='javascript:getPrevPage("+page+","+totalPage+",\""+key+"\",\""+select+"\","+other+");' class='pagination__prev'>prev</a>"
							+"<a href='javascript:getNextPage("+page+","+totalPage+",\""+key+"\",\""+select+"\","+other+");' class='pagination__next'>next</a></div>");
				})
			});
		}
	</script>

	<script type="text/javascript">
		//获取电影的类别
		function getmtype(movieId){
			var result="";
			$.ajax({
				type:"GET",
				url:"getmtypes",
				data:{
					movieId:movieId
				},
				async : false,
				success:function(data){
					//对返回值进行拼接
					for(var i=0;i<data.length;i++){
						if(i==0){
							result+=data[i].moviename;
						}else{
							result+=" | "+data[i].moviename;
						}
					}
					
				},
				dataType:"json"
			});
			return result;
		}
		
		//获取电影的评分
		function getmscore(movieId){
			var result="";
			$.ajax({
				type:"GET",
				url:"getmscore",
				data:{
					movieId:movieId
				},
				async : false,
				success:function(data){
					
					//给result赋值
					if(data == ""){
						result = 0;
					}else{
						result=data[0].score ;	
					}
					
				},
				dataType:"json"
			});
			return result;
		}
		
		//获取该电影有多少人看过
		function getmtcount(movieId){
			var result;
			$.ajax({
				type:"GET",
				url:"getmtnum",
				data:{
					movieId:movieId
				},
				async : false,
				success:function(data){
					//给result赋值
					result=data ;
				},
				dataType:"json"
			});
			return result;
		}
		
	</script>

	<script type="text/javascript">
		function changeTime(time){
		    if(time){
		        var oDate = new Date(time*1),
		            oYear = oDate.getFullYear(),
		            oMonth = oDate.getMonth()+1,
		            oDay = oDate.getDate()
		            oTime = oYear +'-'+ getBz(oMonth) +'-'+ getBz(oDay);//拼接时间
		        return oTime;
		    }else{
	       		 return "";
		    }
		}
		//时间补零
		function getBz(num){
		    if(parseInt(num) < 10){
		        num = '0'+num;
		    }
		    return num;
		}
		
		function getInt(total){
			return Math.ceil(total/3);
		}
	</script>

	<script type="text/javascript">
		function ordermovie(factor, page) {
			$("#orderall").removeClass("item-active");
			$("#orderrelease").removeClass("item-active");
			$("#orderpopularity").removeClass("item-active");
			$("#ordercomments").removeClass("item-active");
			$("#order"+factor).addClass("item-active");
			
			MovieOrder(factor,page);
			
		}
	</script>

	<script>
	    //获取焦点的时候进行ajax的查询联想词
		$("#search-content").focus(function() {
			var type = $("#search-sort").val();
			console.log("1"+type);
			if(type == "电影名"){
				type = "moviename";
			}else if(type =="类型"){
				type = "mTypeName";
			}else if(type =="导演"){
				type = "director";
			}else if(type =="主演"){
				type = "mainactor";
			}else if(type =="地区"){
				type = "place";
			}else if(type =="语言"){
				type = "language";
			}
			console.log("2"+type);
			//动态键传值
			var data = {};
			key = type;
			value = type;
			data[key] = value;
			$.ajax({
				url : "gws",
				type : "post",
				dataType : "json",
				data : data,

				success : auto
			})
		});
		// 按钮搜索 
		$("#btnsearch").click(function() {
			var select = $("#search-sort").val();
			var key = $("#search-content").val();
			var page = 1;
			MovieByLike(select, key , page);
		})
	    
		//点击联想词直接搜索
		function auto(data) {
			console.log(data);
			$("#search-content").autocomplete({
				source : data,
				select : function(event, ul) {
					var type = $("#search-sort").val();
					var keys = ul.item.value;
					
					MovieByLike(type, keys , 1);
				}
			});
		}
		
		//分页生成新的页面，下一页点击调取的函数
		function getNextPage(page,totalPage,keys,select){
			//自增
			page+=1;
			//判断用户当前是否还有分页
			if(page<=totalPage){
				//刷新下一页
				freshNext(page,keys,select);
				//提示
				layui.use('layer', function(){
					  var layer = layui.layer;
					  layer.msg('第'+page+'页');
				});
			}else{
				//提示
				layui.use('layer', function(){
					  var layer = layui.layer;
					  layer.msg('没有更多啦');
				});
			}
			
		}
		//分页生成新的页面，上一页点击调取的函数
		function getPrevPage(page,totalPage,keys,select){
			//判断用户当前是否还有分页
			//自增
			page=page-1;
			//判断用户当前是否还有分页
			if(page>0){
				//刷新上一页
				freshNext(page,keys,select);
				//提示
				layui.use('layer', function(){
					  var layer = layui.layer;
					  layer.msg('第'+page+'页');
				});
			}else{
				//提示
				layui.use('layer', function(){
					  var layer = layui.layer;
					  layer.msg('当前是第1页');
				});
			}
			
		}
		//刷新下一页
		function freshNext(page,keys,select){
			/* 根据获取值判断是从搜索框还是排序  */
			if(keys == "nokey"){
				MovieOrder(select,page);
			}else{
				MovieByLike(select,keys,page);
			}
		}
	</script>
	
	<script type="text/javascript">
		// 改变收藏状态的函数
		function updmcoll(movieId){

			//用户id
			var userId = <%=session.getAttribute("userid")%> ;
			
			//获取用户当前的收藏状态,这边要填电影id，用户id
			var collstatus=getmcoll(movieId,userId);
			
			//如果返回值为0，说明用户没收藏，所以要添加收藏
			if(collstatus==0){
				$.ajax({
					url:"addct",
					type:"POST",
					contentType:"application/json",
					data:JSON.stringify({
						 users: {
				                userid: userId
				         },
				         movies: {
				                movieid: movieId
				         }
					}),
					success:function(data){
						//清空文本
						$("#rate"+movieId).text("");
						//追加
						$("#rate"+movieId).append(""
							+"<i class='layui-icon layui-icon-star-fill' style='font-size: 25px; color: rgb(255, 184, 0);'>"
							+"</i>&nbsp;取消收藏");
						if(data.code==200){
							layui.use('layer', function(){
								  var layer = layui.layer;
								  
								  layer.msg('收藏成功！可到我的收藏查看');
								});	
						}
					},
					dataType:"json"
				});
			}
			//如果返回值为1，说明用户已经收藏，所以要取消收藏
			if(collstatus!=0){
				$.ajax({
					url:"delctbyum",
					type:"POST",
					contentType:"application/json",
					data:JSON.stringify({
						 users: {
				                userid: userId
				         },
				         movies: {
				                movieid: movieId
				         }
					}),
					success:function(data){
						//清空文本
						$("#rate"+movieId).text("");
						//追加
						$("#rate"+movieId).append(""
							+"<i class='layui-icon layui-icon-star' style='font-size: 25px; color: rgb(255, 184, 0);'>"
							+"</i>&nbsp;点击收藏");
						
						if(data.code==200){
							layui.use('layer', function(){
								  var layer = layui.layer;
								  
								  layer.msg('取消收藏成功');
								});
						}
					},
					dataType:"json"
				});
			}
		}
		
		//获取用户当前是否收藏的状态
		function getmcoll(movieId,userId){
			var result="";
			$.ajax({
				url:"docoll",
				type:"POST",
				contentType:"application/json",
				data:JSON.stringify({
					 users: {
			                userid: userId
			         },
			         movies: {
			                movieid: movieId
			         }
				}),
				async : false,
				success:function(data){
					//给result赋值
					result=data;
				},
				dataType:"json"
			});
			return result;
		}
		
	</script>
		
	<script type="text/javascript">
		$(function(){
			var key = '<%=request.getParameter("key")%>';
			var select = '<%=request.getParameter("select")%>';
			if(key == "null"){
				key = "";
			}
			if(select == "null"){
				select = "";
			}

			MovieByLike(select, key , null);
		})
	</script>
	<!-- 获取数据总量 -->
	<script type="text/javascript">
		$(function() {
			/* 全部   */
			$.get("MovieByOrderCount?factor=all", function(data) {
				$("#allcount").val(data);
			})
			//获取今日排行
			$.get("getmtoday",function(data){
				$.each(data,function(i,v){
					//拼接
					$("#moviestoday").append("<li style='margin-left:-40px'><a href=movie-page-full.jsp?movieid="+v.movieid+" class='category__item'>"+(i+1)+"、"+v.moviename+"</a></li>");
				});
				
			});
			//获取即将上映的高分榜
			$.get("getmsoon",function(data){
				console.log(data);
				$.each(data,function(i,v){
					//拼接
					$("#moviessoon").append("<li style='margin-left:-40px'><a href=movie-page-full.jsp?movieid="+v.movieid+" class='category__item'>"+(i+1)+"、"+v.moviename+"</a></li>");
				});
				
			});
		})
	</script>

</body>
</html>
